<script lang="ts" setup>
import { reactive, onMounted, nextTick } from 'vue';
import { getCurrentInstance, setStorage, setStorageSync, reLaunch, showToast } from '@tarojs/taro';
import getAuthCode from 'gdt-jsapi/getAuthCode';
import authConfig from 'gdt-jsapi/authConfig';
import CommonPageQueryEmpty2 from '/@/assets/image/icon/common-page-query-empty-2.png';
import { DD_USER_LOGIN, DD_TOKEN_GET } from '/@/api/modules/ding-talk/dd-user';
import { logInDev } from '/@/utils/index';

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as {
  /**
   * 租户 ID
   */
  corpId?: string;
  /**
   * 授权码
   */
  auth_code?: string;
  /**
   * 授权码
   */
  code?: string;
  /**
   * 来源页面
   */
  toPage?: string;
};

const state = reactive<{
  /**
   * 需要前往登录页
   */
  needToLogin: boolean;
  msg: string;
}>({
  needToLogin: false,
  msg: '授权登录中...',
});

/**
 * @function 钉钉登录
 */
function login(authCode?: string) {
  if (!authCode) return;

  DD_USER_LOGIN({ authCode })
    .then((res) => {
      setStorage({
        key: 'token',
        data: res.token,
        success: () => {
          setStorageSync('loginType', 'dg-work');
          reLaunch({
            url: params.toPage ? decodeURIComponent(params.toPage) : '/pages/index/index',
          });
        },
      });
    })
    .catch((err) => {
      showToast({
        title: err.comResp.err || err.comResp.tip,
      });
    });
}

/**
 * @function 钉钉授权
 */
function ddAuthCode(authCode?: string) {
  if (!authCode) return;

  DD_TOKEN_GET({
    authCode,
  })
    .then((res) => {
      authConfig({
        ticket: res.appToken,
        jsApiList: ['onAudioPlayEnd'],
      })
        .then((res) => {
          logInDev(res);
        })
        .catch((err) => {
          logInDev(err);
        });
    })
    .catch((err) => {
      showToast({
        title: err.comResp.err || err.comResp.tip,
      });
    });
}

onMounted(() => {
  nextTick(() => {
    if (params.auth_code || params.code) {
      login(params.auth_code || params.code);

      ddAuthCode(params.auth_code || params.code);
      return;
    }

    getAuthCode({
      corpId: params.corpId,
    })
      .then((res) => {
        logInDev(res);
        login(res.auth_code || res.code);
      })
      .catch((err) => {
        state.needToLogin = true;
        state.msg = err;
        setTimeout(() => {
          reLaunch({ url: `/pages/user/login/index?toPage=${params.toPage}` });
        }, 3000);
      });

    getAuthCode({
      corpId: params.corpId,
    })
      .then((res) => {
        logInDev(res);
        ddAuthCode(res.auth_code || res.code);
      })
      .catch((err) => {
        state.msg = err;
      });
  });
});
</script>

<template>
  <view class="dg-work-login">
    <view class="dg-work-login__wrapper">
      <image
        v-if="state.needToLogin"
        class="dg-work-login__to-login-page-img"
        :src="CommonPageQueryEmpty2"
      />
      <view v-if="state.needToLogin" class="dg-work-login__to-login-page-wrapper">
        正在跳转登录页...
      </view>
      <view class="dg-work-login__msg-wrapper">{{ state.msg }}</view>
    </view>
  </view>
</template>

<style lang="scss">
.dg-work-login {
  width: 100%;
  height: 100vh;
  font-size: 30px;
  color: #333;
  display: flex;
  align-items: center;
  justify-content: center;

  &__wrapper {
    text-align: center;
    width: 70vw;
  }

  &__to-login-page-img {
    width: 340px;
  }

  &__to-login-page-wrapper {
    font-weight: bold;
    font-size: 42px;
  }

  &__msg-wrapper {
    font-size: 24px;
    color: #666;
    margin: 20px auto 0;
  }
}
</style>
